<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools :title="'123'">
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template slot="right">
          <el-button v-allow="'import_employee'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button v-allow="'export_employee'" type="danger" size="small" @click="hExport">导出excel</el-button>
          <el-button type="primary" size="small" @click="showVisible = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'workNumber'}">
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column label="头像" width="120">
            <template v-slot="{row}">
              <!-- <img :src="row.staffPhoto" alt=""> -->
              <ImageHolder :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{row}">
              {{ row.formOfEmployment ? '正式' : '非正式' }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" width="160" sortable />
          <!-- <el-table-column prop="" label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes,prev, pager, next, jumper"
            :current-page="page"
            :total="total"
            :page-size="size"
            :page-sizes="[3,5,7]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 添加员工 -->
    <el-dialog
      title="添加员工"
      width="50%"
      :visible.sync="showVisible"
      @close="$refs.addRef.resetForm()"
    >
      <AddEmp ref="addRef" @success="hSuccess" @close="showVisible=false" />
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog
      :visible.sync="showDialogRole"
      title="分配角色"
      width="50%"
      @close="$refs.roleRef.loadRole()"
    >
      <AssignRole ref="roleRef" :cur-id="curId" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import AssignRole from './assignRole.vue'
import AddEmp from './addEmp.vue'
const TYPE_MAP = { 1: '正式', 2: '非正式', 3: 'AAA', 4: 'BBB', 5: 'CCC', 6: 'DDD' }

export default {
  components: { AddEmp, AssignRole },
  data() {
    return {
      list: [],
      total: 0, // 总条数
      page: 1,
      size: 3,
      curId: '',
      showVisible: false,
      showDialogRole: false
    }
  },
  created() {
    this.initEmployeeList()
  },
  methods: {
    // 点击分配角色
    hAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
    },
    // 用来处理数据的函数
    formatData(rows) {
      // 表头（英文的表单需要转中文）
      const enHeader = Object.keys(rows[0])
      const mapObj = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const header = enHeader.map(en => mapObj[en])
      // 内容
      const data = rows.map(obj => {
        // 对应聘形式进行转换
        obj.formOfEmployment = TYPE_MAP[obj.formOfEmployment]
        return Object.values(obj)
      })
      return { header, data }
    },
    // 导出表格
    hExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发ajax请求，获取数据
        const { data: res } = await getEmployeeList({ page: this.page, size: this.size })
        console.log(res)
        console.log('从后端获取的数据', res)

        const { header, data } = this.formatData(res.rows)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 子组件添加成功
    hSuccess() {
      this.showVisible = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      // 刷新
      this.initEmployeeList()
    },
    // 删除员工
    async doDel(id) {
      try {
        // 1. 调接口
        await delEmployee(id)
        // 2.提示
        this.$message.success('删除成功')
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        // 3.刷新
        this.initEmployeeList()
      } catch (e) {
        // console.dir(e)
        this.$message.error(e.message)
      }
    },
    hDel(id) {
      this.$confirm('确定要删除吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    hSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.size = val
      this.initEmployeeList()
    },
    hCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.initEmployeeList()
    },
    async initEmployeeList() {
      const { data: res } = await getEmployeeList({ page: this.page, size: this.size })
      console.log(res)
      this.list = res.rows
      this.total = res.total
    }
  }
}
</script>
